package com.wrl.mmall.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class FTPUtil {

    private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
    private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
    private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");

    private String ip;
    private int port;
    private String user;
    private String pwd;
    private FTPClient ftpClient;

    /**
     * 上传，对外只提供这一个方法
     *
     * @param fileList 可以批量上传
     * @return
     * @throws IOException 异常抛给业务层
     */
    public static boolean uploadFile(List<File> fileList) throws IOException {

        //端口是固定的21
        FTPUtil ftpUtil = new FTPUtil(ftpIp, 21, ftpUser, ftpPass);
        logger.info("开始连接ftp服务器");
        boolean result = ftpUtil.uploadFile("img", fileList);
        logger.info("结束上传，上传结果:{}", result);
        return result;
    }

    /**
     * 上传的具体逻辑
     *
     * @param
     * @throws IOException
     */
    private boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
        boolean uploaded = false;
        FileInputStream fis = null;
        //如果ftp服务器连接成功
        boolean connectSuccess = connectServer(this.getIp(), this.getPort(), this.getUser(), this.getPwd());
        if (connectSuccess) {
            try {
                //改变工作目录（如果是空，表示不切换）
                ftpClient.changeWorkingDirectory(remotePath);
                //缓冲区
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                //设置为二进制文件类型，防止乱码
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                //打开被动模式
                ftpClient.enterLocalPassiveMode();
                if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                    ftpClient.disconnect();
                } else {
                    logger.info("FTP连接成功!");
                    for (File fileItem : fileList) {
                        fis = new FileInputStream(fileItem);
                        //存储文件
                        ftpClient.storeFile(fileItem.getName(), fis);
                    }
                    uploaded = true;
                }
            } catch (IOException e) {
                logger.error("上传文件异常", e);
                uploaded = false;
                e.printStackTrace();
            } finally {
                //释放连接
                fis.close();
                ftpClient.disconnect();
            }
        }
        return uploaded;
    }

    /**
     * 连接ftp服务器
     *
     * @return
     */
    private boolean connectServer(String ip, int port, String user, String pwd) {
        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            //连接
            ftpClient.connect(ip);
            //登录
            isSuccess = ftpClient.login(user, pwd);
            System.out.println("ftp连接状态：" + isSuccess);
        } catch (IOException e) {
            logger.error("连接ftp服务器异常", e);
        }

        return isSuccess;
    }


    public FTPUtil(String ip, int port, String user, String pwd) {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
    }


    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }


}
